Write your first program in React – the easy way
To work with React in the web browser, we need to include two libraries: React and ReactDOM.
Prior to version 0.14, ReactDOM was part of React and only recently they were separated as two different libraries to facilitate React Native. ReactDOM contains ReactDOM.render()
method which is a DOM specific function used to render everything. That’s all you need to know for right now.
We also need an HTML element that will be used as a container for our first application. Both libraries are available on Facebook CDN.
<script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
- You can also download the files from Facebook’s official repository of React at Github.
- You can place your JavaScript code in a separate file but it must be loaded in the page after React has been loaded.
- ReactDOM is needed to render React elements in the browser.
Steps to Create your First Program in React
Let’s start with creating a new file index.html using your favorite editor.
<!doctype HTML> <html lang="en"> <head> <title>My first program in React</title> </head> <body> <div id="root"> </div> </body> </html>
The react code will be placed right before the <div> tag. You can think of it as a container of our first application. If you are confused regarding the use of HTML into JavaScript, well, this isn’t exactly HTML. It is JSX, which is a completely separate entity from the React, but it makes life much easier when rendering React in a web browser.
For example, with JSX you can write the following:
const greeting = <h1> Hello World</h1>
JSX will transpile into JavaScript behind the scene. You need a preprocessor to translate your code in the browser. For this example, we are using Babel. The CDN of Babel is:
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.js"></script>
Putting everything together, we have the following piece of code:
<!doctype HTML> <html lang="en"> <head> <title>First program in React</title> </head> <body> <div id="root"> </div> <script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <script type="text/babel"> ReactDOM.render( <h1>hello world</h1>, document.getElementById('root') ); </script> </body> </html>
The usage of ReactDOM
ReactDOM.render()
takes two parameters:
- What you want to render. Example:
<h1> hello world</h1>
- Where you want to render. Example:
document.getElementById("root")
In the next lesson, we will learn about the React components. If you have any question about this lesson, feel free to leave it in the comment section below and I will reply at the earliest.
React Installation & Configuration | Tutorial Home | React Components |
Comments